package com.tubeonfire.model.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.tubeonfire.entity.Author;

public class AuthorModel {
	private static final Logger log = Logger.getLogger(AuthorModel.class
			.getName());

	private static Objectify ofy;

	private static Cache cache = null;

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private int limit = 12;
	
	private int page = 1;

	private int totalResult = 0;

	private int totalPage = 1;

	private static String cacheSide = "backEnd_";

	private static String cachePrefix = "authorModel_";

	private static TreeMap<String, String> mapCacheKey = new TreeMap<String, String>();

	private List<Author> listResult = new ArrayList<Author>();
	
	public int getTotalPage() {
		totalPage = totalResult / limit;
		if ((totalResult % limit) > 0) {
			totalPage += 1;
		}
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getTotalResult() {
		return totalResult;
	}

	public void setTotalResult(int totalResult) {
		this.totalResult = totalResult;
	}

	public List<Author> getListResult() {
		return listResult;
	}

	public void setListResult(List<Author> listResult) {
		this.listResult = listResult;
	}

	public static void init() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				ObjectifyService.register(Author.class);
			} catch (Exception e) {
				isRegisted = false;
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
			opts = new ObjectifyOpts().setSessionCache(true);
		}
		ofy = ObjectifyService.begin(opts);
	}

	public AuthorModel() {
		init();
	}

	@SuppressWarnings("unchecked")
	public static void insert(Author obj) {
		init();
		if (cache != null) {
			String prefix = cachePrefix + "id_" + obj.getUri();
			cache.put(prefix, obj);
			clearModelCache();
		}
		ofy.put(obj);
	}

	public static void delete(Author obj) {
		init();
		String prefix = cachePrefix + "id_" + obj.getUri();
		if (cache != null && cache.containsKey(prefix)) {
			cache.remove(prefix);
			clearModelCache();
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public static Author getById(String id) {
		try {
			init();
			Author obj = new Author();
			String prefix = cachePrefix + "id_" + id;
			if (cache != null && cache.containsKey(prefix)) {
				obj = (Author) cache.get(prefix);
			} else {
				try {
					obj = ofy.get(new Key<Author>(Author.class, id));
					cache.put(prefix, obj);
				} catch (Exception e) {
					obj = null;
				}
			}
			return obj;
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public void prepareList() {
		init();
		listResult = new ArrayList<Author>();
		String prefix = cachePrefix + "page_" + page + "_limit_" + limit;
		if (cache != null && cache.containsKey(prefix)) {
			listResult = (List<Author>) cache.get(prefix);
			totalResult = (Integer) cache.get(cacheSide
					+ "allAuthorTotalResult");
			limit = (Integer) cache.get(cacheSide + "allPlaylistLimit");
		} else {
			int start = (page - 1) * limit;
			Query<Author> q = ofy.query(Author.class).order("-indexDate");
			totalResult = q.count();
			q = q.limit(limit).offset(start);
			for (Author obj : q) {
				listResult.add(obj);
			}
			if (listResult.size() > 0) {
				cache.put(prefix, listResult);
				cache.put(cacheSide + "allPlaylistTotalResult", totalResult);
				cache.put(cacheSide + "allPlaylistLimit", limit);
			}
		}
	}

	public static void clearModelCache() {
		init();
		try {
			if (mapCacheKey != null && mapCacheKey.size() > 0) {
				for (String key : mapCacheKey.keySet()) {
					cache.remove(key);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
